<template>
  <div class="container">
    <div class="card-container">
      <div style="margin-bottom:0;" @change="tabsChange" type="card" :tabBarStyle="{'marginBottom':0,'marginTop':'20px'}">
        <div :key="0" tab="总表" style="background-color: #f0f2f5;padding: 20px 0 0 0;">
          <div class="search">
            <a-form-model layout="inline">
              <a-row type="flex" >
                <!-- <a-col :xxl="5" :xl="12" :lg="24" :md="24" :sm="24" :xs="24" >
                  <a-form-item label="选择时间" :labelAlign="labelAlign" :labelCol="{xxl:{span: 6},xl:{span: 4},lg:{span:4},md:{span:4},sm:{span:4},xs:{span: 12}}" :wrapperCol="{xxl:{span: 17},xl:{span: 19},lg:{span:24},md:{span: 24},sm:{span: 24},xs:{span: 24}}" style="width: 100%">
                    <a-select v-model="chartTimeSelect" @change="selectChange">
                      <a-select-option :value="1">当日</a-select-option>
                      <a-select-option :value="2">昨日</a-select-option>
                      <a-select-option :value="3">过去一周</a-select-option>
                      <a-select-option :value="4">过去30天</a-select-option>
                      <a-select-option :value="5">本月</a-select-option>
                      <a-select-option :value="6">本季度</a-select-option>
                      <a-select-option :value="7">自定义</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>   -->
                <a-col :xxl="6" :xl="8" :lg="24" :md="24" :sm="24" :xs="24" v-if="chartTimeSelect == 7" >
                  <a-form-item label="自定义时间" :labelAlign="labelAlign" :labelCol="{xxl:{span: 6},xl:{span: 5},lg:{span:4},md:{span:4},sm:{span:4},xs:{span: 12}}" :wrapperCol="{xxl:{span: 17},xl:{span: 18},lg:{span:24},md:{span: 24},sm:{span: 24},xs:{span: 24}}" style="width: 100%">
                    <a-range-picker
                      :allowClear="false"
                      :ranges="{ '昨天': [moment().add(-1, 'days'), moment().add(-1, 'days')], '过去7天': [moment().add(-7, 'days'), moment().add(-1, 'days')], 
                                '过去30天': [moment().add(-30, 'days'), moment().add(-1, 'days')] }"
                      :defaultValue="[moment(form.start_date), moment(form.end_date)]"
                      :disabled-date="disabledDate" @change="formDateChange" 
                      v-if="chartTimeSelect == 7" style="width: 100%;"
                    />
                  </a-form-item>
                </a-col>
                <a-col :xxl="2" :xl="2" :lg="2" :md="2" :sm="2" :xs="2" >
                  <a-form-item :labelCol="{xxl:{span: 8},xl:{span: 8},md:{span:4},sm:{span:3},xs:{span: 12}}" :wrapperCol="{xxl:{span: 16},xl:{span: 16},md:{span: 20},sm:{span: 24},xs:{span: 24}}" style="width: 100%">
                    <a-button :loading="outputLoading" type="primary" @click="handle_export">导出报表</a-button>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
          <div class="totalContainer" >
            <a-row type="flex" justify="space-between" v-if="false">
              <a-col :xxl="5" :xl="7" :md="11" :sm="24" :xs="24" class="total-col total-item">
                <div class="title">展现</div>
                <div class="p">
                  <countTo :startVal='0' :endVal='parseFloat((totalList.impression || 0))' :duration='800' :decimals="0"></countTo>
                </div>
              </a-col>
              <a-col :xxl="6" :xl="8" :md="11" :sm="24" :xs="24" class="total-col total-item">
                <div class="title">转化率</div>
                <div class="p" style="height: 100%;">
                  <countTo :startVal='0' :endVal='parseFloat((totalList.cvr*100).toFixed(2))' :duration='800' :decimals="2"></countTo>%
                </div>
              </a-col> 
              <a-col :xxl="6" :xl="8" :md="11" :sm="24" :xs="24" class="total-col total-item">
                <div class="title">总消费</div>
                <div class="p" style="height: 100%;">
                  <countTo :startVal='0' :endVal='parseFloat((totalList.cost || 0))' :duration='800' :decimals="2"></countTo>
                </div>
              </a-col> 
              <a-col :xxl="6" :xl="7" :md="11" :sm="24" :xs="24" class="total-col total-item" style="padding:0;background-color: transparent;">
                <a-row type="flex" justify="space-between" style="height:100%;">
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;">
                    <div class="title">商品成单成本</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.dsOcpcConversionsDetail90Cost || 0))' :duration='800' :decimals="2"></countTo>
                    </div>
                  </a-col>
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;" offset="2">
                    <div class="title">直播间成单成本</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.dsOcpcConversionsDetail80Cost || 0))' :duration='800' :decimals="2"></countTo>
                    </div>
                  </a-col>  
                </a-row>
              </a-col>
              <a-col :xxl="5" :xl="8" :md="11" :sm="24" :xs="24" class="total-col total-item" style="padding:0;background-color: transparent;">
                <a-row type="flex" justify="space-between" style="height:100%;">
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;">
                    <div class="title">点击</div>
                    <div class="p">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.click || 0))' :duration='800' :decimals="0"></countTo>
                    </div>
                  </a-col>
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;" offset="2">
                    <div class="title">点击率</div>
                    <div class="p">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.ctr*100).toFixed(2))' :duration='800' :decimals="2"></countTo>%
                    </div>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :xxl="6" :xl="8" :md="11" :sm="24" :xs="24" class="total-col total-item" style="padding:0;background-color: transparent;">
                <a-row type="flex" justify="space-between" style="height:100%;">
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;">
                    <div class="title">商品成单量</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.dsOcpcConversionsDetail90 || 0))' :duration='800' :decimals="0"></countTo>
                    </div>
                  </a-col>
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;" offset="2">
                    <div class="title">直播间成单量</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.dsOcpcConversionsDetail80 || 0))' :duration='800' :decimals="0"></countTo>
                    </div>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :xxl="6" :xl="12" :md="11" :sm="24" :xs="24" class="total-col total-item" style="padding:0;background-color: transparent;">
                <a-row type="flex" justify="space-between" style="height:100%;">
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;">
                    <div class="title">商品成单金额</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.dsOcpcConversionsDetail90Amount || 0))' :duration='800' :decimals="2"></countTo>
                    </div>
                  </a-col>
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;" offset="2">
                    <div class="title">直播间成单金额</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.dsOcpcConversionsDetail80Amount || 0))' :duration='800' :decimals="2"></countTo>
                    </div>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :xxl="6" :xl="11" :md="11" :sm="24" :xs="24" class="total-col total-item" style="padding:0;background-color: transparent;">
                <a-row type="flex" justify="space-between" style="height:100%;">
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;">
                    <div class="title">商品客单价</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.atv90 || 0))' :duration='800' :decimals="2"></countTo>
                    </div>
                  </a-col>
                  <a-col :span="11" class="total-col total-item" style="margin-top:0;" offset="2">
                    <div class="title">直播间客单价</div>
                    <div class="p" style="height: 100%;">
                      <countTo :startVal='0' :endVal='parseFloat((totalList.atv80 || 0))' :duration='800' :decimals="2"></countTo>
                    </div>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
            <div style="background-color:#ffffff;padding:20px;margin-top:20px;">
              <standard-table
                rowKey="id"
                id="zhanghuTable"
                :loading='loading'
                :columns="columns"
                :dataSource="dataSource"
                :expandedRowKeys='expandedRowKeys'
                :pagination="{showTotal:total => `共 ${total} 条数据`, pageSize: pageSize,showLessItems: true, showSizeChanger:true}"
                @clear="onClear"
                @change="onChange"
                @onExpand="onExpand"
              >
                
                <div slot="hour" slot-scope="{record}">
                  {{(record.hour) + '点'}}
                </div>
                <div slot="ctr" slot-scope="{record}">
                  {{(record.ctr*100).toFixed(2) + '%'}}
                </div>
                <div slot="cvr80" slot-scope="{record}">
                  {{(record.cvr80*100).toFixed(2) + '%'}}
                </div>
                <div slot="cvr90" slot-scope="{record}">
                  {{(record.cvr*100).toFixed(2) + '%'}}
                </div>
                <div slot="cost" slot-scope="{record}">
                  {{(record.cost).toFixed(2)}}
                </div>
                <div slot="dsOcpcConversionsDetail80Amount" slot-scope="{record}">
                  {{parseFloat(record.dsOcpcConversionsDetail80Amount).toFixed(2)}}
                </div>
                <div slot="cost80" slot-scope="{record}">
                  {{(record.cost80).toFixed(2)}}
                </div>
                <div slot="cost90" slot-scope="{record}">
                  {{(record.cost90).toFixed(2)}}
                </div>
                <div slot="dsOcpcConversionsDetail90Amount" slot-scope="{record}">
                  {{parseFloat(record.dsOcpcConversionsDetail90Amount).toFixed(2)}}
                </div>
                <div slot="dsOcpcConversionsDetail90" slot-scope="{record}">
                  {{parseFloat(record.dsOcpcConversionsDetail90).toFixed(2)}}
                </div>
                <div slot="dsOcpcConversionsDetail80Cost" slot-scope="{record}">
                  {{record.dsOcpcConversionsDetail80Cost == 0 ? '-' : parseFloat(record.dsOcpcConversionsDetail80Cost).toFixed(2)}}
                </div>
                <div slot="dsOcpcConversionsDetail90Cost" slot-scope="{record}">
                  {{record.dsOcpcConversionsDetail90Cost == 0 ? '-' : parseFloat(record.dsOcpcConversionsDetail90Cost).toFixed(2)}}
                </div>
              </standard-table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import StandardTable from '@/components/table/StandardTable'
import {getAccountReportByHour} from '@/api/shuju/shuju'
import countTo from 'vue-count-to';
import {getBdAccountList, getOptimizerList} from '@/api/xinxiliu/account'
import moment from 'moment'
import {getAccountSummary,getAccountHour} from '@/api/dianshang/dianshang'
import FileSaver from 'file-saver';
import xlsx from 'xlsx';
// import moment from 'moment'

const columns = [
  {
    title: '小时',
    width: 120,
    dataIndex: 'hour',
    defaultSortOrder: 'descend',
    scopedSlots: { customRender: 'hour' },
    sorter: (a,b) => a.hour - b.hour,
  },
  {
    title: '展现',
    width: 100,
    dataIndex: 'impression',
    sortDirections:['descend','ascend'],
    sorter: (a,b) => a.impression - b.impression,
  },
  {
    title: '点击',
    dataIndex: 'click',
    sortDirections:['descend','ascend'],
    sorter: (a,b) => a.click - b.click,
  },
  {
    title: '点击率',
    dataIndex: 'ctr',
    scopedSlots: { customRender: 'ctr' },
    sorter: (a,b) => a.ctr - b.ctr,
  },
  {
    title: '总消费',
    width: 100,
    dataIndex: 'cost',
    scopedSlots: { customRender: 'cost' },
    sortDirections:['descend','ascend'],
    sorter: (a,b) => a.cost - b.cost,
  },
  {
    title: '商品成单量',
    dataIndex: 'dsOcpcConversionsDetail90',
    sortDirections:['descend','ascend'],
    sorter: (a,b) => a.dsOcpcConversionsDetail90 - b.dsOcpcConversionsDetail90,
  },
  {
    title:'商品成单成本',
    dataIndex: 'dsOcpcConversionsDetail90Cost',
    scopedSlots: { customRender: 'dsOcpcConversionsDetail90Cost' },
  },
  {
    title:'商品GMV',
    dataIndex: 'dsOcpcConversionsDetail90Amount',
    scopedSlots: { customRender: 'dsOcpcConversionsDetail90Amount' },
  },
  {
    title:'商品转化率',
    dataIndex: 'cvr',
    scopedSlots: { customRender: 'cvr90' },
  },
  // {
  //   title: '直播成单量',
  //   dataIndex: 'dsOcpcConversionsDetail80',
  //   sortDirections:['descend','ascend'],
  //   sorter: () => {},
  // },
  // {
  //   title:'直播成单成本',
  //   dataIndex: 'dsOcpcConversionsDetail80Cost',
  //   scopedSlots: { customRender: 'dsOcpcConversionsDetail80Cost' },
  // },
  // {
  //   title:'直播GMV',
  //   dataIndex: 'dsOcpcConversionsDetail80Amount',
  //   scopedSlots: { customRender: 'dsOcpcConversionsDetail80Amount' },
  // },
  // {
  //   title:'直播转化率',
  //   dataIndex: 'cvr80',
  //   scopedSlots: { customRender: 'cvr80' },
  // },
]

const columns2 = [
  {
    title: '时间',
    width: 200,
    dataIndex: 'date',
  },
  {
    title: '账户',
    width: 200,
    dataIndex: 'userName'
  },
  {
    title: '展现',
    width: 200,
    dataIndex: 'impression',
    scopedSlots: { customRender: 'impression' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '点击',
    width: 200,
    dataIndex: 'click',
    scopedSlots: { customRender: 'click' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '消费',
    width: 200,
    dataIndex: 'cost',
    defaultSortOrder: 'descend',
    scopedSlots: { customRender: 'cost' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '点击率',
    width: 200,
    dataIndex: 'ctr',
    scopedSlots: { customRender: 'ctr' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '商品支付成功量',
    width: 200,
    dataIndex: 'ctProductPaySuccess',
    scopedSlots: { customRender: 'ctProductPaySuccess' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
  {
    title: '直播间成单量',
    width: 200,
    dataIndex: 'ctLiveOrderConversions',
    scopedSlots: { customRender: 'ctLiveOrderConversions' },
    sortDirections:['descend','ascend'],
    sorter: () => {},
  },
]

export default {
  data() {
    return {
      moment,
      tabsKey:0,
      superid:0,

      userData:[],

      chartTimeSelect:7,
      totalList:{
        atv80:0, // 直播客单价
        atv90:0, // 商品客单价
        cost80:0, // 直播总消费
        cost90:0, // 商品总消费
        dsOcpcConversionsDetail80:0, // 直播间成单量
        dsOcpcConversionsDetail90:0, // 商品成单量
        dsOcpcConversionsDetail80Amount:0, //直播间成单总金额
        dsOcpcConversionsDetail90Amount:0, //商品支付成功总金额
        dsOcpcConversionsDetail80Cost: 0, //播间成单成本
        dsOcpcConversionsDetail90Cost: 0, //商品成单成本
        impression: 0,
        click: 0,
        cost: 0,
        cpc: 0,
        ctr:0,
        cvr:0,
        // act:0,
        // pct:0,
        // ctLiveOrderConversions: 0,
        // ctProductPaySuccess:0,
        // liveact:0, 
        // liveCost:0,
        // livepct:0,
        // liveOrderData: {
        //   cost: 0,
        //   liveOrderAmountConversions: 0,
        //   liveOrderConversions: 0,
        // }
      },

      columns:columns,
      loading:false,
      expandedRowKeys:[],
      changeKey:'cost',
      changeOrder:'DESC',
      dataSource:[],

      columns2:columns2,
      loading2:false,
      expandedRowKeys2:[],
      changeKey2:'cost',
      changeOrder2:'DESC',
      dataSource2:[],
      dataSource2Total:[],
      keyWord:'',

      hourData:[],
      chartSelect:'cost',
      myChart:null,
      chartIndex:0,
      hourArr:[],
      chartAutoPlay:true,
      chartAutoPlayTimeOut: 3000,
      marks:{},
      marksList:[],
      marksValue:0,
      chartTimeoutFunc:null,
      spin:false,
      youhuashiId:0,
      youhuashi:[], // 优化师列表

      page:1,
      page2:1,
      pageSize: 10,

      form:{
        start_date: moment().add(-1, 'days').format("YYYY-MM-DD"),
        end_date: moment().add(-1, 'days').format("YYYY-MM-DD"),
      },

      outputLoading:false,
      labelAlign:'right',
    }
  },
  created(){
    this.init()
  },
  mounted(){
    this.watchWindowWidth()
  },
  methods:{
    init(){
      if(this.tabsKey === 0){
        // this.getTotalData()
        this.getRiData()
        // this.getUserData()
        // this.getOptimizerList()
      }else if(this.tabsKey == 1){
        this.getRiData()
      }else if(this.tabsKey == 2){
        this.getXiaoshiData()
        this.getChartData()
      }
    },
    getUserData(){
      getBdAccountList({}).then((res) => {
        if(res.errcode == 0){
          let arr = []
          for(let i of res.data){
            if(i.pid == 0){
              arr.push(i)
            }
          }
          this.userData = arr
        }
      });
    },
    getTotalData(){
      let params = {
        type:this.chartTimeSelect,
        superid:this.superid,
      }
      if(this.chartTimeSelect == 7){
        Object.assign(params, this.form)
      }
      if(this.youhuashiId != 0){
        params.optid = this.youhuashiId
      }
      this.getRiData()
      getAccountSummary(params).then((res) => {
        if(res.errcode == 0){
          this.totalList = res.data
        }
      });
    },
    getOptimizerList(){
      // 获取优化师列表
      getOptimizerList({}).then((res) => {
        console.log(res)
        if(res.errcode == 0){
          this.youhuashi = res.data
        }
      });
    },
    getRiData(){
      const _this = this;
      this.loading = true;
      let params = {
        column:this.changeKey,
        sortrule:this.changeOrder,
        type:this.chartTimeSelect,
        superid:this.superid,
      }
      if(this.chartTimeSelect == 7){
        let form = JSON.parse(JSON.stringify(this.form))
        form.end_date = form.end_date + " 23:59:59"
        Object.assign(params, form)
      }
      if(this.youhuashiId != 0){
        params.optid = this.youhuashiId
      }
      // getAccountReportByDate(params).then((res) => {
        getAccountHour(params).then((res) => {
        _this.loading = false;
        if(res.errcode == 0){
          let idx = 1
          for(let item of res.data){
            item.id = idx
            idx++
          }
          _this.dataSource = res.data
        }
      }).catch(()=>{
        _this.loading = false;
      });
    },
    getXiaoshiData(){
      const _this = this;
      this.loading2 = true;
      let params = {
        column:this.changeKey2,
        sortrule:this.changeOrder2
      }
      getAccountReportByHour(params).then((res) => {
        _this.loading2 = false;
        if(res.errcode == 0){
          let idx = 1
          for(let item of res.data){
            item.id = idx
            let huanbi = {
              act: this.getHuanbi(item,'act'),
              click: this.getHuanbi(item,'click'),
              cost: this.getHuanbi(item,'cost'),
              cpc: this.getHuanbi(item,'cpc'),
              ctLiveOrderConversions: this.getHuanbi(item,'ctLiveOrderConversions'),
              ctProductPaySuccess: this.getHuanbi(item,'ctProductPaySuccess'),
              ctProductPaySuccessAmount: this.getHuanbi(item,'ctProductPaySuccessAmount'),
              ctProductPaySuccessAmountROI: this.getHuanbi(item,'ctProductPaySuccessAmountROI'),
              ctr: this.getHuanbi(item,'ctr'),
              impression: this.getHuanbi(item,'impression'),
              pct: this.getHuanbi(item,'pct'),
            }
            item.huanbi = huanbi
            idx++
          }
          _this.dataSource2 = res.data
          _this.dataSource2Total = res.data
          if(_this.keyWord != ''){
            _this.onSearch(_this.keyWord)
          }
        }
      });
    },
    getChartData(){
      if(this.$refs.chartLineRef){
        this.$refs.chartLineRef.init()
      }
      getAccountReportByHour({}).then((res) => {
        if(res.errcode == 0){
          this.hourData = res.data
          setTimeout(() => {
            this.$refs.chartLineRef.setHourData()
          }, 0);
          // this.createChart()
        }
      });
    },
    createChart(){
      let data = JSON.parse(JSON.stringify(this.hourData)) 
      if(this.chartTimeoutFunc){
        clearTimeout(this.chartTimeoutFunc)
      }
      this.chartIndex = 0
      this.marksValue = 0
      // 循环data，设置hour，并取出userName和hour
      let hourArr = [] // 包含hour、userName数组及seriesData数组
      for(let item of data){
        item.ctr = (item.ctr*100).toFixed(2)
        item.cost = new Number(item.cost).valueOf().toFixed(2)
        // let hour = moment(item.date).format('H')
        let hour = item.hour
        // item.hour = hour
        // 判断字符串转数组
        let seriesDataChild = typeof item[this.chartSelect] == 'number'?item[this.chartSelect]:new Number(item[this.chartSelect]).valueOf()
        if(!hourArr.find(e=>e.hour == hour)){
          hourArr.push({
            hour,
            userNameArr: [item.userName],
            seriesData: [seriesDataChild]
          })
        }else{
          let f = hourArr.find(e=>e.hour == hour)
          f.userNameArr.push(item.userName)
          f.seriesData.push(seriesDataChild)
        }
      }
      // 按时间顺序排序
      hourArr.sort((a,b)=>a.hour - b.hour)
      console.log('hour',hourArr)
      this.hourArr = hourArr
      let yAxisData = hourArr[this.chartIndex].userNameArr
      let seriesData = hourArr[this.chartIndex].seriesData
      //设置marks
      let marks = {}
      let marksList = []
      let len = 1
      for(let item of hourArr){
        if(item.seriesData.length < 9){
          len++
          continue
        }
        if(marksList.length > 0){
          let location = Math.ceil(marksList.length*100/(hourArr.length-len))
          // console.log('location',location,item.hour)
          marks[location] = item.hour + '时'
          marksList.push({
            value:location,
            index:marksList.length
          })
        }else{
          marks[0] = item.hour + '时'
          marksList.push({ 
            value:0,
            index:0
          })
        }
      }
      // console.log(marks,marksList)
      this.marks = marks
      this.marksList = marksList

      this.myChart = echarts.init(document.getElementById('chart-main'));
      const options = {
        xAxis: {
          max: 'dataMax'
        },
        yAxis: {
          type: 'category',
          data: yAxisData,
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 4 //y轴数据大于10个时展示10个（0-9),否则 0 - yAxisData.length-1
        },
        series: [
          {
            realtimeSort: true,
            type: 'bar',
            data: seriesData,
            label: {
              show: true,
              position: 'right',
              valueAnimation: true
            }
          }
        ],
        legend: {
          show: true
        },
        animationDuration: 0,
        animationDurationUpdate: 3000,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear'
      }
      this.myChart.setOption(options)
      setTimeout(() => {
        this.chartRun()
      }, 0);
    },
    sliderChange(value){
      this.chartIndex = this.marksList.find(o=>o.value == value).index
      this.chartRun()
    },
    chartRun(){
      if(this.chartAutoPlay){
        this.chartIndex++
        this.marksValue = new Number(this.marksList.find(e=>e.index == this.chartIndex).value).valueOf()
        // console.log(this.marksValue)
      }
      let yAxisData = this.hourArr[this.chartIndex].userNameArr
      let seriesData = this.hourArr[this.chartIndex].seriesData
      // console.log(this.chartIndex,seriesData,yAxisData)
      this.myChart.setOption({
        xAxis: {
          max: 'dataMax'
        },
        yAxis: {
          type: 'category',
          data: yAxisData,
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 4, //y轴数据大于10个时展示10个（0-9),否则 0 - yAxisData.length-1
        },
        series: [
          {
            realtimeSort: true,
            type: 'bar',
            data: seriesData,
            label: {
              show: true,
              position: 'right',
              valueAnimation: true
            }
          }
        ],
        legend: {
          show: true
        },
        animationDuration: 0,
        animationDurationUpdate: this.chartAutoPlayTimeOut,
        animationEasing: 'linear',
        animationEasingUpdate: 'linear'
      })
      if(this.chartIndex < this.hourArr.length - 1&&this.chartAutoPlay){
        this.chartTimeoutFunc = setTimeout(() => {
          this.chartRun()
        }, this.chartAutoPlayTimeOut + 300);
      }
    },
    refresh(){
      this.spin = true
      this.createChart()
      setTimeout(() => {
        this.spin = false
      }, 800);
    },

    getSorter2(sorter){
      if(sorter.column){
        this.changeKey2 = sorter.column.dataIndex
        switch(sorter.order){
          case "ascend":
            this.changeOrder2 = 'ASC'
            break
          case "descend":
            this.changeOrder2 = 'DESC'
            break
        }
      }else{
        this.changeKey2 = ''
        this.changeOrder2 = ''
      }
    },
    onClear2() {
      this.$message.info('您清空了勾选的所有行')
    },
    onChange2(pagination, filters, sorter,) {
      // console.log(pagination, filters, sorter)
      if(this.page2 == pagination.current){
        this.getSorter2(sorter)
        this.getXiaoshiData()
      }
      this.page2 = pagination.current
    },
    onExpand2(bool, row){
      if(bool){
        this.expandedRowKeys2.push(row.id)
      }else{
        let idx = this.expandedRowKeys2.findIndex(e=>e == row.id)
        this.expandedRowKeys2.splice(idx,1)
      }
    },
    onSearch(userName){
      this.keyWord = userName
      if(userName != ''){
        this.dataSource2 = this.dataSource2Total.filter(o=>o.userName == userName)
      }else{
        this.dataSource2 = this.dataSource2Total
      }
    },

    getSorter(sorter){
      if(sorter.column){
        this.changeKey = sorter.column.dataIndex
        switch(sorter.order){
          case "ascend":
            this.changeOrder = 'ASC'
            break
          case "descend":
            this.changeOrder = 'DESC'
            break
        }
      }else{
        this.changeKey = ''
        this.changeOrder = ''
      }
    },
    onClear() {
      this.$message.info('您清空了勾选的所有行')
    },
    onChange(pagination, filters, sorter,) {
      // console.log(pagination, filters, sorter)
      this.pageSize = pagination.pageSize
      if(this.page == pagination.current){
        this.getSorter(sorter)
        // this.getRiData()
      }
      this.page = pagination.current
    },
    onExpand(bool, row){
      if(bool){
        this.expandedRowKeys.push(row.id)
      }else{
        let idx = this.expandedRowKeys.findIndex(e=>e == row.id)
        this.expandedRowKeys.splice(idx,1)
      }
      console.log("onExpand", bool, row,this.expandedRowKeys)
    },
    tabsChange(){
      this.init()
    },
    selectYouhuashi(e){
      this.youhuashiId = e
      this.init()
    },
    getHuanbi(item,key){
      let today = item[key]?item[key]:0
      let yesdata = item.yesdata?item.yesdata[key]?item.yesdata[key]:0:0
      let huanbi = '-'
      if(yesdata != 0 && today != 0){
        huanbi = (today - yesdata)/yesdata*100
        huanbi = huanbi.toFixed(2)
      }else if(yesdata == 0 && today == 0){
        huanbi = 0
      }
      return huanbi
    },
    selectChange(){
      this.getTotalData()
    },
    formDateChange(e){
      if(e.length == 0){return}
      this.form.start_date = e[0].format("YYYY-MM-DD")
      this.form.end_date = e[1].format("YYYY-MM-DD")
      this.getRiData()
    },
    disabledDate(current){
      return current && ( current < moment().endOf('day').add(-31, 'days') || current > moment().endOf('day').add(-1, 'days')) ;
    },
    handle_export() {
      this.outputLoading = true
      setTimeout(() => {
        this.pageSize = 999999999
      }, 300);
      // this.dataSource.unshift({
      //   userName: '合计',
      //   impression: this.totalList.impression,
      //   click: this.totalList.click,
      //   ctr: this.totalList.ctr,
      //   cost: parseFloat((this.totalList.cost || 0)),
      //   dsOcpcConversionsDetail90: parseFloat((this.totalList.dsOcpcConversionsDetail90 || 0)),
      //   dsOcpcConversionsDetail90Cost: parseFloat((this.totalList.dsOcpcConversionsDetail90Cost || 0)),
      //   dsOcpcConversionsDetail90Amount: parseFloat((this.totalList.dsOcpcConversionsDetail90Amount || 0)),
      //   cvr90: this.totalList.cvr90,
      //   dsOcpcConversionsDetail80: parseFloat((this.totalList.dsOcpcConversionsDetail80 || 0)),
      //   dsOcpcConversionsDetail80Cost: parseFloat((this.totalList.dsOcpcConversionsDetail80Cost || 0)),
      //   dsOcpcConversionsDetail80Amount: parseFloat((this.totalList.dsOcpcConversionsDetail80Amount || 0)),
      //   cvr80: this.totalList.cvr80,
      // })
      setTimeout(() => {
        var xlsxParam = {
          raw: true
        }; //转换成excel时，使用原始的格式，这样导出的时候数字过长不会变成科学计数法
        let xlsxName = this.xlsxName('账户小时报表')
        let workbook = xlsx.utils.book_new();
        let ws1 = xlsx.utils.table_to_sheet(document.querySelector('#zhanghuTable'), xlsxParam);
        xlsx.utils.book_append_sheet(workbook, ws1, xlsxName);
        // 列转换数字格式
        for (let key in ws1) {
          if(ws1[key]['t']){
            ws1[key]['t'] = "n"
          }
        }
        let wbout = xlsx.write(workbook, {
            bookType: 'xlsx',
            bookSST: true,
            type: 'array'
        });
        try {
          FileSaver.saveAs(
          new Blob([wbout], {
              type: 'application/octet-stream;charset=utf-8"'
          }), xlsxName + '.xlsx');
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout);
        }finally{
          this.dataSource.shift()
          this.pageSize = 10
          this.outputLoading = false
        }
        return wbout;
      }, 600);
    },
    xlsxName(name){
      let xlsxName = name + '-' + moment(this.form.start_date).format("YYYY年MM月DD日") + '至' + moment(this.form.end_date).format("YYYY年MM月DD日")
      return xlsxName
    },
    watchWindowWidth(){
      let width = window.innerWidth
      if(width<=1600){
        this.labelAlign = "left"
      }else{
        this.labelAlign = "right"
      }
      window.onresize = () => {
        width = window.innerWidth
        if(width<=1200){
          this.labelAlign = "left"
        }else{
          this.labelAlign = "right"
        }
      }
    }
  },
  watch:{
    chartAutoPlay(val){
      if(val){
        this.chartRun()
      }
    }
  },
  computed:{
    isoptimizer(){
      return this.$store.state.user.userInfo.isoptimizer
    }
  },
  components:{
    StandardTable,
    countTo,
  }
}
</script>

<style lang="less" scoped>
.container{
  .card{
    margin-bottom: 20px;
  }
  .area{
    display: flex;
    align-items: center;
  }
  .fontGreen{
    margin-left: 10px;
    color: #41b883;
  }
  .fontRed{
    margin-left: 10px;
    color: #c96168;
  }
}
.search{
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
}
.card-container {
  overflow: hidden;
}
.card-container > .ant-tabs-card > .ant-tabs-content {
  height: 120px;
  margin-top: -16px;
}

.card-container > .ant-tabs-card > .ant-tabs-content > .ant-tabs-tabpane {
  background: #fff;
  padding: 16px;
}

.card-container > .ant-tabs-card > .ant-tabs-bar {
  border-color: #fff;
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab {
  border-color: transparent;
  background: transparent;
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab-active {
  border-color: #fff;
  background: #fff;
}

.totalContainer{
  background-color: #f0f2f5;
}
.total-col{
  background-color: #fff;
  border-radius: 8px;
  padding: 10px 20px;
  margin-top: 20px;
}
.total-item{
  display: flex;
  flex-direction: column;
  .title{
    // font-weight: 700;
    // font-size: 22px;
    // color: #545b66;
    color: rgba(0,0,0,.45);
    font-size: 14px;
    line-height: 22px;
    white-space: nowrap;
  }
  .p{
    color: #222222;
    font-size: 22px;
    margin-top: 20px;
  }
}
</style>